package com.example.network;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private TextView responseText;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        responseText = findViewById(R.id.response_text);
        // 发送Android自带的HttpURLConnection
        findViewById(R.id.send_request).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequestWithHttpURLConnection();
            }
        });
        // 清理屏幕
        findViewById(R.id.clear_screen).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                responseText.setText("");
            }
        });
        // 发送OkHttp请求
        findViewById(R.id.send_okhttp_request).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequestWithOkHttp();
            }
        });
    }

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 1.创建一个OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();
                    // 2.创建一个Request对象
                    Request request = new Request.Builder()
                            .url("http://www.baidu.com")
                            .build();
                    // 3.发送请求
                    Response response = client.newCall(request).execute();
                    // 4.获取数据
                    String responseBody = response.body().string();
                    // 5.处理数据
                    showResponse(responseBody);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void sendRequestWithHttpURLConnection() {
        // 开启线程发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("https://www.baidu.com");
                    // 1.建立连接
                    connection = (HttpURLConnection) url.openConnection();
                    // 2.设置请求类型
                    connection.setRequestMethod("GET");
                    // 3.设置参数
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    // 4.获取输入流
                    InputStream in = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    // 5.读取数据
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    // 6.处理数据
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            // 7.断开连接
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 在这里进行ui操作
                responseText.setText(response);
            }
        });
    }
}